<template>
  <div>
     <el-page-header content="学员管理">
      <template #extra>
        <div class="page-header-extra">
          <el-input
            v-model="searchQuery"
            placeholder="请输入搜索的内容"            style="width: 200px; margin-right: 10px;"
            clearable
            @clear="fetchStudents"
          />
          <el-button type="primary" @click="addDialogVisible = true">增加学员</el-button>
        </div>
      </template>
      </el-page-header>
    <el-table :data="filteredStudents" style="width: 100%">
      <el-table-column label="序号" width="80">
                    <template #default="scope">
                        {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
                    </template>
      </el-table-column>
      <el-table-column prop="username" label="姓名" />
      <el-table-column prop="phone" label="电话" />
      <el-table-column prop="birthday" label="出生年月" />
      <el-table-column prop="license_type" label="驾照类型" />
      <el-table-column prop="address" label="地址" />
      <el-table-column prop="current_level" label="学习阶段" />
      <el-table-column label="操作" width="180" fixed="right" align="center">
        <template #default="scope">
          <div class="operation-cell">
            <el-button size="small" type="primary" icon="el-icon-edit" @click="editMerchant(scope.row)">
              编辑
            </el-button>
            <el-button size="small" type="danger" icon="el-icon-delete" @click="deleteMerchant(scope.row.student_id)">
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="editDialogVisible" title="编辑学员信息" width="50%">
      <el-form :model="editForm"  label-width="120px" ref="editFormRef" :rules="formRules">
        <!-- 用户名/姓名 -->
        <el-form-item label="用户名/姓名" prop="username">
          <el-input v-model="editForm.username" />
        </el-form-item>

        <!-- 密码 -->
<el-form-item label="密码" prop="password">
  <el-input
    v-model="editForm.password"
    :type="showOriginalPassword ? 'text' : 'password'"
    show-password
    placeholder="输入新密码（留空保持原密码）"
  />
  <el-button
    size="small"
    @click="showOriginalPassword = !showOriginalPassword"
  >
    {{ showOriginalPassword ? '隐藏' : '显示' }}密码
  </el-button>
  <div v-if="showOriginalPassword" class="original-password-hint">
    原始密码: {{ editForm.password }}
  </div>
</el-form-item>
        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" type="email" />
        </el-form-item>

        <!-- 手机号 -->
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone" />
        </el-form-item>

        <!-- 性别 -->
        <el-form-item label="性别" prop="gender">
          <el-select v-model="editForm.gender" placeholder="请选择">
            <el-option label="男" value="MALE" />
            <el-option label="女" value="FEMALE" />
            <el-option label="其他" value="OTHER" />
          </el-select>
        </el-form-item>

        <!-- 出生日期 -->
        <el-form-item label="出生日期" prop="birthday">
          <el-date-picker
            v-model="editForm.birthday"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="选择日期"
          />
        </el-form-item>

        <!-- 地址 -->
        <el-form-item label="地址" prop="address">
          <el-input v-model="editForm.address" />
        </el-form-item>

        <!-- 当前阶段 -->
        <el-form-item label="当前阶段" prop="current_level">
          <el-select v-model="editForm.current_level" placeholder="请选择">
            <el-option label="科目一" value="科目一" />
            <el-option label="科目二" value="科目二" />
            <el-option label="科目三" value="科目三" />
            <el-option label="科目四" value="科目四" />
          </el-select>
        </el-form-item>

        <!-- 驾照类型 -->
        <el-form-item label="驾照类型" prop="license_type">
          <el-select v-model="editForm.license_type" placeholder="请选择">
            <el-option label="C1" value="C1" />
            <el-option label="C2" value="C2" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </div>
      </template>
    </el-dialog>
     <!-- 新增学员表单 -->
    <el-dialog v-model="addDialogVisible" title="新增学员" width="50%">
      <el-form :model="addForm" label-width="120px" ref="addFormRef" :rules="formRules">
        <!-- 用户名/姓名 -->
        <el-form-item label="用户名/姓名" prop="username">
          <el-input v-model="addForm.username" />
        </el-form-item>

        <!-- 密码 -->
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="addForm.password"
            :type="'password'"
            show-password
            placeholder="请输入密码"
          />
        </el-form-item>

        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" type="email" />
        </el-form-item>
        <!-- 身份证号 -->
        <el-form-item label="身份证号" prop="id_number">
          <el-input v-model="addForm.id_number" />
        </el-form-item>

        <!-- 手机号 -->
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="addForm.phone" />
        </el-form-item>

        <!-- 性别 -->
        <el-form-item label="性别" prop="gender">
          <el-select v-model="addForm.gender" placeholder="请选择">
            <el-option label="男" value="MALE" />
            <el-option label="女" value="FEMALE" />
            <el-option label="其他" value="OTHER" />
          </el-select>
        </el-form-item>

        <!-- 出生日期 -->
        <el-form-item label="出生日期" prop="birthday">
          <el-date-picker
            v-model="addForm.birthday"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="选择日期"
          />
        </el-form-item>

        <!-- 地址 -->
        <el-form-item label="地址" prop="address">
          <el-input v-model="addForm.address" />
        </el-form-item>

        <!-- 当前阶段 -->
        <el-form-item label="当前阶段" prop="current_level">
          <el-select v-model="addForm.current_level" placeholder="请选择">
            <el-option label="科目一" value="科目一" />
            <el-option label="科目二" value="科目二" />
            <el-option label="科目三" value="科目三" />
            <el-option label="科目四" value="科目四" />
          </el-select>
        </el-form-item>

        <!-- 驾照类型 -->
        <el-form-item label="驾照类型" prop="license_type">
          <el-select v-model="addForm.license_type" placeholder="请选择">
            <el-option label="C1" value="C1" />
            <el-option label="C2" value="C2" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddForm">确认</el-button>
        </div>
      </template>
    </el-dialog>
     <!-- 分页 -->
                <el-pagination
                    class="pagination"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[10, 20, 50, 100]"
                    :page-size="pageSize"
                    :total="displayTotal"
                    layout="total, sizes, prev, pager, next, jumper"

                ></el-pagination>

  </div>
</template>

<script setup>
import {ref, onMounted, watch, computed} from 'vue'
import { ElMessage,ElMessageBox } from 'element-plus'
import requestUtil from '@/util/request.js'

const students = ref([])
const allStudents = ref([]) // 新增：存储所有学生数据用于前端过滤
// 分页
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
// 搜索字段
const searchQuery = ref('')
// 添加表单
const addDialogVisible = ref(false)
const addFormRef = ref()
const addForm = ref({
  username: '',
  password: '',
  email: '',
  phone: '',
  id_number:'',
  fullname: '',
  gender: '',
  birthday: '',
  address: '',
  enrollment_date: '', // 隐藏字段，不在表单显示但会提交
  current_level: '',
  license_type: ''
})

// 编辑表单
const editFormRef = ref()
const editDialogVisible = ref(false)
const showOriginalPassword = ref(false)
const editForm = ref({
  student_id: 0,
  username: '',
  password:'',
  email: '',
  phone: '',
  fullname: '',
  gender: '',
  birthday: '',
  address: '',
  enrollment_date: '', // 隐藏字段，不在表单显示但会提交
  current_level: '',
  license_type: ''
})
// 修改分页显示的总数
const displayTotal = computed(() => {
  return searchQuery.value ? filteredStudents.value.length : total.value;
});
// 表单验证规则
const formRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: ['blur', 'change'] }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  license_type: [
    { required: true, message: '请输入驾照类型', trigger: 'blur' }
  ],
  id_number: [
  { required: true, message: '请输入身份证号', trigger: 'blur'},
  { pattern: /^(^\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/, message: '身份证号格式不正确', trigger: 'blur'}
  ]
}
// 在 script setup 部分添加计算属性
// 新增：计算属性实现前端过滤
const filteredStudents = computed(() => {
  if (!searchQuery.value) {
    return students.value;
  }

  const query = searchQuery.value.toLowerCase();
  return allStudents.value.filter(student => {
    return (
      (student.username && student.username.toLowerCase().includes(query)) ||
      (student.fullname && student.fullname.toLowerCase().includes(query)) ||
      (student.phone && student.phone.includes(query)) ||
      (student.address && student.address.toLowerCase().includes(query)) ||
      (student.current_level && student.current_level.includes(query)) ||
      (student.license_type && student.license_type.includes(query))
    );
  });
});

/**
 * 每页条数变化
 */
const handleSizeChange = (size) => {
    pageSize.value = size;
    currentPage.value = 1; // 重置到第一页
};

/**
 * 当前页码变化
 */
const handleCurrentChange = (page) => {
    currentPage.value = page;
};
// 获取学员列表
// 修改后的获取学员列表方法
const fetchStudents = async () => {
  try {
    const response = await requestUtil.get('/student/msg',{
        page: currentPage.value,
        page_size: pageSize.value
    })
    students.value = response.data.data
    allStudents.value = response.data.data // 保存所有数据用于前端过滤
    total.value = response.data.total;
  } catch (error) {
    console.error('获取学生列表失败:', error)
    ElMessage.error('获取学员列表失败')
  }
}
// 掩码显示原密码（安全处理）


// 编辑学员
const editMerchant = async (row) => {
   const res = await requestUtil.get(`/student/msg/${row.student_id}`)
   console.log('获取到的学员数据:', res.data.data);
  editForm.value = {
    ...res.data.data, // 初始化时明确不传密码
    // 确保入学日期不为空，若无值则使用当前日期
    enrollment_date: res.data.data.enrollment_date || new Date().toISOString().split('T')[0]
  }
  editDialogVisible.value = true
}
// 移除原有的搜索框防抖监听器
watch(searchQuery, (newVal) => {
  if (newVal) {
    // 使用前端过滤时，重置分页到第一页
    currentPage.value = 1;
    students.value = filteredStudents.value;
    total.value = filteredStudents.value.length;
  } else {
    // 如果搜索框为空，恢复显示所有数据
    students.value = allStudents.value;
    total.value = allStudents.value.length;
  }
});


// 提交新增表单
const submitAddForm = async () => {
   // 在提交表单之前设置 enrollment_date 为当前日期
  addForm.value.enrollment_date = new Date().toISOString().split('T')[0];
  // 验证表单
  try {
    const valid = await addFormRef.value.validate();
    if (!valid) {
      ElMessage.error('请填写完整信息');
      return;
  }


    await requestUtil.post('/student/add', addForm.value)
    addDialogVisible.value = false
    ElMessage.success('新增成功')
    await fetchStudents()
  } catch (error) {
    console.error('新增失败:', error)
     if (error.response && error.response.data) {
      console.log('后端返回的错误信息:', error.response.data);
    }
    ElMessage.error(`新增失败: ${error.response?.data?.message || error.message}`)
  }
}
// 提交更新表单
const submitForm = async() => {
    try {
    // 验证表单
      const valid = await editFormRef.value.validate()
        if (!valid) {
          ElMessage.error('请填写完整信息')
          return
        }


      await requestUtil.put(
          `/student/update/${editForm.value.student_id}`,
          editForm.value
      )
      editDialogVisible.value = false
      ElMessage.success('更新成功')
      await fetchStudents()
    } catch (error) {
      console.error('更新失败:', error)
      ElMessage.error(`更新失败: ${error.response?.data?.message || error.message}`)
    }
}

// 删除学员
const deleteMerchant = async (id) => {
  try {
    // 添加确认提示
    await ElMessageBox.confirm(
      '确定要删除这个学员吗？此操作不可恢复！',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    const response = await requestUtil.del(`/student/delete/${id}`)
    if (response.data?.status === 200) {
      ElMessage.success('删除成功')
      await fetchStudents()
    } else {
      ElMessage.error(response.data?.message || '删除失败')
    }
  } catch (error) {
    // 用户取消删除操作
    if (error === 'cancel' || error === 'close') {
      ElMessage.info('已取消删除')
      return
    }

    console.error('删除学员失败:', error)
    ElMessage.error(error.response?.data?.message || '删除失败')
  }
}

onMounted(() => {
  fetchStudents()
})
</script>

<style scoped>
.operation-cell .el-button {
  margin-right: 8px;
}

.operation-cell .el-button:last-child {
  margin-right: 0;
}
/* 分页样式 */
.pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}
.page-header-extra {
  display: flex;
  align-items: center;
}

</style>